/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.dao;

import org.ipti.br.tag.entity.AdditionalInfo;
import org.ipti.br.tag.entity.AdditionalInfoType_;
import org.ipti.br.tag.entity.AdditionalInfo_;
import org.ipti.br.tag.entity.Person_;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author root
 */
@Stateless
public class AdditionalInfoFacade extends AbstractFacade<AdditionalInfo> {

    @PersistenceContext(unitName = "TAG2PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public AdditionalInfoFacade() {
        super(AdditionalInfo.class);
    }

    @Override
    public void create(AdditionalInfo additionalInfo) {
        getEntityManager().persist(additionalInfo);
    }

    @Override
    public void edit(AdditionalInfo additionalInfo) {
        getEntityManager().merge(additionalInfo);
    }

    public List<AdditionalInfo> findAddInfosPerPerson(Long personID) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<AdditionalInfo> cq = cb.createQuery(AdditionalInfo.class);
        Root<AdditionalInfo> from = cq.from(AdditionalInfo.class);
        Predicate predicate = cb.equal(from.get(AdditionalInfo_.person).get(Person_.id), personID);
        cq.where(cb.and(predicate));
        cq.orderBy(cb.asc(from.get(AdditionalInfo_.additionalInfoType).get(AdditionalInfoType_.acronym)));

        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<AdditionalInfo> modifiedAddInfoBetweenDate(Calendar initialDate, Calendar finalDate, Long serialNumber) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<AdditionalInfo> cq = cb.createQuery(AdditionalInfo.class);
        Root<AdditionalInfo> from = cq.from(AdditionalInfo.class);
        Predicate predicate1 = cb.notEqual(from.get(AdditionalInfo_.serialNumber), serialNumber);
        Predicate predicate2 = cb.greaterThanOrEqualTo(from.get(AdditionalInfo_.lastModified), initialDate);
        Predicate predicate3 = cb.lessThan(from.get(AdditionalInfo_.lastModified), finalDate);
        cq.where(cb.and(predicate1, predicate2, predicate3));

        return getEntityManager().createQuery(cq).getResultList();
    }
}
